package com.mialab.servlet_demo;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ResponsePicServlet")
public class ResponsePicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ResponsePicServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应消息头Content-Type
		response.setContentType("image/jpeg");
		// 获取ServletContext对象
		ServletContext context = super.getServletContext();
		// 获取读取服务器端文件的输入流
		InputStream is = context.getResourceAsStream("/images/bridge.jpg");
		// 获取ServletOutputStream输出流
		ServletOutputStream os = response.getOutputStream();
		int i = 0;
		while ((i = is.read()) != -1) {
			os.write(i);// 向输出流中写入二进制数据
		}
		is.close();
		os.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
